<script setup lang="ts">
import type { EditorProps } from './types';

import { computed, onBeforeUnmount, shallowRef } from 'vue';

import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

const props = withDefaults(defineProps<EditorProps>(), {
  modelValue: '',
  height: '500px',
  disabled: false,
  mode: 'default',
  placeholder: '请输入内容',
});

const emit = defineEmits(['update:modelValue']);
// 默认工具栏配置
const toolbarConfig = {};
const editorConfig = { placeholder: props?.placeholder };

const editorContent = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  },
});

// 编辑器实例（必须使用 shallowRef）
const editorRef = shallowRef<Editor | null>(null);
// const editorContent = ref(props.modelValue);

// 初始化编辑器
const handleCreated = (editor: Editor) => {
  editorRef.value = editor;
  // 禁用状态处理
  if (props.disabled) editor.disable();
};

// 销毁实例
onBeforeUnmount(() => {
  editorRef.value?.destroy();
});
</script>

<template>
  <div class="editor-container">
    <Toolbar
      class="toolbar"
      :editor="editorRef"
      :default-config="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="{ height: props?.height, overflowY: 'hidden' }"
      v-model="editorContent"
      :default-config="editorConfig"
      @on-created="handleCreated"
      :mode="mode"
    />
  </div>
</template>

<style>
@import '@wangeditor/editor/dist/css/style.css';

.editor-container {
  border: 1px solid #ddd;
  border-radius: 4px;
}

.toolbar {
  border-bottom: 1px solid #ddd;
}
</style>
